$(function(){
    getMessages(index);
})

function loadingMore() {
    index++;
    getMessages(index);
}

$("#addMessageTitle").click(function(){
    if(!session_user){
        parent.showFrame(content_path+'/user/login',500,400);
    }
});
$("#addMessageContent").click(function(){
    if(!session_user){
        parent.showFrame(content_path+'/user/login',500,400);
    }
});

function getMessages(page) {
    var postdata = {"productID":productID,"page":page};
    $.ajax({
        url: content_path+"/note/getMessage",
        type:'GET',
        data:postdata,
        dataType:'json',
        success:function(data){
            if(data["result"]==1){
                var messages = data["list"];
                $("#loadinggif").remove();
                for(var i=0; i<messages.length; i++) {
                    addMessageDiv(messages[i]);
                }
                if(messages.length<5){
                    $(".endtag button").hide();
                    $(".endtag").append("<h4 class='text-info'>到底了~</h4>");
                }
            }
        }
    });
}

function addMessageDiv(message) {
    var mID = message.messageID;
    let tpl =
        `<div class="media">
        <div class="media-left"><span class="glyphicon glyphicon-user"></span></div>
        <div id="${"mID-"+mID}" class="media-body">
            <h4 class="media-heading"><small>${message.writer}<i>  发布于 ${message.writeDate}</i></small></h4>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"><strong id="${"mID-"+mID+"_title"}">${message.title}</strong>
                        <small id="${"mID-"+mID+"_more"}" style="cursor:pointer" onclick="getRevert(${mID})" class="btn-xs pull-right">查看回复(${message.count})</small>
                    </h3>
                </div>
                <div id="${"mID-"+mID+"_content"}" class="cont panel-body">${message.content.replace(new RegExp("\n", 'g'),"<br>")}</div>
            </div>
        </div>
    </div>`;

    $("#showNote").append(tpl);
    var moreTag = $("#mID-"+mID+"_more");
    if(session_user){
        moreTag.after(`<small id="${"mID-"+mID+"_ret"}" style="cursor:pointer" onclick="addRevert(${mID},'${message.writer}')" class="btn-xs pull-right">回复</small>`);
        if(session_user == message.writer){
            moreTag.after(`<small id="${"mID-"+mID+"_edit"}" style="cursor:pointer" onclick="updateMessage(${mID})" class="btn-xs pull-right">编辑</small>
                           <small id="${"mID-"+mID+"_del"}" style="cursor:pointer" onclick="deleteMessage(${mID})" class="btn-xs pull-right">删除</small>`);
        }
    }
}

function getRevert(mID) {
    if($("#mID-"+mID+"_hide").val()=="" || $("#mID-"+mID+"_more").html().replace(/.*\((\d+)\)$/, '$1')=="0") return;
    var postdata = {"messageID":mID};
    $.ajax({
        url:content_path+"/note/getRevert",
        type:'GET',
        data:postdata,
        dataType:'json',
        success:function(data){
            if(data["result"]==1){
                var reverts = data["list"];
                for(var i=0; i<reverts.length; i++) {
                    addRevertDiv(reverts[i], mID);
                }
                $("#mID-"+mID+"_more").after(`<small id='${"mID-"+mID+"_hide"}' style="cursor:pointer" onclick="hiddenReverts(${mID})" class="btn-xs pull-right">收起</small></h3>`);
            }
        }
    });
}

function hiddenReverts(mID) {
    $("#mID-"+mID+" .media").remove();
    $("#mID-"+mID+"_hide").remove();
}

function addRevertDiv(revert,mID) {
    var rID = revert.revertID;
    let tpl =
        `<div class="media">
        <div class="media-left"><span class="glyphicon glyphicon-chevron-right"></span></div>
        <div id="${"rID-"+rID}" class="media-body">
            <h4 class="media-heading"><small><span class="glyphicon glyphicon-user"></span> ${revert.writer}<i>  发布于 ${revert.writeDate}</i></small></h4>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"><strong><span class="glyphicon glyphicon-comment"></span></strong>
                    </h3>
                </div>
                <div id="${"rID-"+rID+"_content"}" class="cont panel-body">${revert.content.replace(new RegExp("\n", 'g'),"<br>")}</div>
            </div>
        </div>
    </div>`;
    $("#mID-"+mID).append(tpl);
    if(session_user == revert.writer){
        $("#rID-"+rID+" .panel-title").append(
            `<small id="${"rID-"+rID+"_edit"}" style="cursor:pointer" onclick="updateRevert(${rID},${mID})" class="btn-xs pull-right">编辑</small>
            <small id="${"rID-"+rID+"_del"}" style="cursor:pointer" onclick="deleteRevert(${rID})" class="btn-xs pull-right">删除</small>`);
    }
}

function afterOperate(data) {
    if(data["result"]==1){
        $("#showNote").empty();
        index = 0;
        $(".endtag button").show();
        $(".endtag h4").remove();
        getMessages(index);
    }else {
        alert(data["info"]);
    }
}

function addMessage() {
    if(session_user){
        var mtitle = $("#addMessageTitle").val();
        var mcontent = $("#addMessageContent").val();
        if(mtitle=="" && mcontent=="") return;
        if(mtitle.length>25){
            alert("当前标题长度为"+mtitle.length+"，标题长度不得超过25字符");
            return;
        }
        var postdata = {
            "title":mtitle,
            "content":mcontent,
            "count": 0,
            "productID":productID};

        $.ajax({
            url:content_path+"/note/addMessage",
            type:'POST',
            data:postdata,
            dataType:'json',
            success:function(data){
                afterOperate(data);
                $("#addMessageTitle").val("");
                $("#addMessageContent").val("");
            }
        });
    }else{
        parent.showFrame(content_path+'/user/login',500,400);
    }
}

function addRevert(mID, mwriter) {
    let tpl =
        `<div class="media">
            <div class="media-left"><span class="glyphicon glyphicon-chevron-right"></span></div>
            <div class="media-body">
                <h4 class="media-heading"><span class="glyphicon glyphicon-user"></span> ${session_user}</h4>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title"><strong><span class="glyphicon glyphicon-comment"></span></strong>
                        </h3>
                    </div>
                    <div class="panel-body"><textarea id="${"add-"+mID+"_content"}" placeholder="回复${mwriter}" class="form-control" rows="4"></textarea></div>
                </div>
            </div>
        </div>
        <input type="button" onclick="submitAddRevert(${mID})" class="btn-sm btn-danger pull-right" value="回复">&nbsp;
        <input type="button" onclick="cancel()" class="btn-sm btn-danger pull-right" value="取消">`;
    $("#mID-"+mID+"_content").parent().after(tpl);
}

function submitAddRevert(mID) {
    var mcontent = $("#add-"+mID+"_content").val();
    if(mcontent=="") return;
    var postdata = {
        "messageID":mID,
        "content":mcontent
    };

    $.ajax({
        url:content_path+"/note/addRevert",
        type:'POST',
        data:postdata,
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}

function deleteMessage(mID) {
    $.ajax({
        url:content_path+"/note/deleteMessage",
        type:'POST',
        data: {"messageID":mID},
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}

function updateMessage(mID) {
    var titleTag = $("#mID-"+mID+"_title");
    var contentTag = $("#mID-"+mID+"_content");
    var mcontent = contentTag.html();
    var mtitle = titleTag.text();
    titleTag.replaceWith(`<input id="${"mID-"+mID+"_title"}" type="text" class="form-control" value="${mtitle}">`);
    contentTag.empty();
    contentTag.append(`<textarea class="form-control" rows="${strCharPosition(mcontent,"<br>")+3}">${mcontent.replace(new RegExp("<br>", 'g'),"\n")}</textarea>`);
    contentTag.append(`<input type="button" onclick="cancel()" class="btn-sm btn-danger pull-right" value="取消">&nbsp;`);
    contentTag.append(`<input type="button" onclick="submitUpdateMessage(${mID})" class="btn-sm btn-danger pull-right" value="修改">`);
    $("#mID-"+mID+"_more").hide();
    $("#mID-"+mID+"_edit").hide();
    $("#mID-"+mID+"_del").hide();
    $("#mID-"+mID+"_ret").hide();
}

function getDate() {
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
    var time = new Date().Format("yyyy-MM-dd hh:mm:ss");
    return time.toString();
}

function submitUpdateMessage(mID) {
    var mtitle = $("#mID-"+mID+"_title").val();
    if(mtitle.length>25){
        alert("当前标题长度为"+mtitle.length+"，标题长度不得超过25字符");
        return;
    }
    var mcontent = $("#mID-"+mID+"_content textarea").val();
    if(mtitle==""&&mcontent=="") return;
    var postdata = {
        "messageID":mID,
        "title":mtitle,
        "content":mcontent
    };
    $.ajax({
        url:content_path+"/note/updateMessage",
        type:'POST',
        data:postdata,
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}

function cancel() {
    $("#showNote").empty();
    index = 0;
    getMessages(index);
}

function deleteRevert(rID) {
    $.ajax({
        url:content_path+"/note/deleteRevert",
        type:'POST',
        data: {"revertID":rID},
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}

function updateRevert(rID,mID) {
    var contentTag = $("#rID-"+rID+"_content");
    var rcontent = contentTag.html();
    contentTag.empty();
    contentTag.append(`<textarea class="form-control" rows="${strCharPosition(rcontent,"<br>")+3}">${rcontent.replace(new RegExp("<br>", 'g'),"\n")}</textarea>`);
    contentTag.after(`<input type="button" onclick="cancel()" class="btn-sm btn-danger pull-right" value="取消">&nbsp;`);
    contentTag.after(`<input type="button" onclick="submitUpdateRevert(${rID},${mID})" class="btn-sm btn-danger pull-right" value="修改">`);

    $("#rID-"+rID+"_edit").hide();
    $("#rID-"+rID+"_del").hide();
}

function submitUpdateRevert(rID,mID){
    var rcontent = $("#rID-"+rID+"_content textarea").val();
    if(rcontent=="") return
    var postdata = {
        "revertID":rID,
        "content":rcontent
    };

    $.ajax({
        url:content_path+"/note/updateRevert",
        type:'POST',
        data:postdata,
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}


//检测一个字符在字符串中出现次数，参数字符串，一个字符，返回字符串出现的次数
function strCharPosition(str, char) {
    var pos;
    var arr = [];
    pos = str.indexOf(char);
    while (pos > -1) {
        arr.push(pos);
        pos = str.indexOf(char, pos + 1);
    }
    return arr.length;
}